import type { App } from 'vue'
import {
  UseModuleType,
} from '@apps/_share/enums'
import { useInitApp } from '@apps/_share/hooks'
import { FIRST_SCREEN_LOADING_TITLE } from './settings'

let hasLoading = false

export default async function init(app: App) {
  const {
    installModules,
    setUserInfo,
    setLanguages,
    // setApps,
    setProjects,
    setTitle,
    setTheme,
    setWritingMode,
    setFirstScreenLoading,
    cancelFirstScreenLoading,
  } = useInitApp(app)

  try {
    if (hasLoading) {
      cancelFirstScreenLoading()
    }
    else {
      setFirstScreenLoading({ title: FIRST_SCREEN_LOADING_TITLE })
    }
    hasLoading = true

    installModules([
      UseModuleType.PINIA,
      UseModuleType.UI,
      UseModuleType.WUJIE,
      UseModuleType.I18N,
      UseModuleType.DIRECTIVE,
    ], () => {
      Object.values(import.meta.glob('./modules/*.ts', { eager: true })).forEach((i: any) => {
        const isNeedInstall = [UseModuleType.ROUTER].includes(i?.moduleType)

        if (isNeedInstall)
          i?.install(app)
      })
    })

    await setUserInfo()
    await setLanguages()
    // await setApps()
    await setProjects()

    setTitle()
    setTheme()
    setWritingMode()
  }
  finally {
    setTimeout(() => {
      cancelFirstScreenLoading()
    }, 0)
  }
}
